package com.topdt.jbpm.web.struts.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.web.ActionResult;
import com.thx.log.LogUtil;
import com.topdt.jbpm.dto.View;
import com.topdt.jbpm.form.FormHandle;
import com.topdt.jbpm.model.Activity;
import com.topdt.jbpm.model.AppHandle;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Control;
import com.topdt.jbpm.model.Field;
import com.topdt.jbpm.service.ActivityService;
import com.topdt.jbpm.service.ApplicationService;
import com.topdt.jbpm.service.ControlService;
import com.topdt.jbpm.service.FieldService;
import com.topdt.jbpm.utils.ModuleConstant;
import com.topdt.jbpm.utils.ObjectUtils;

@Namespace("/workflow")
@Action(value = "fieldOption",
		results = {
		@Result(name = "list", location = "/workflow/field/fieldAuthority.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" })
		}
)
@Controller
@Scope("prototype")

public class FieldOptionAction extends CurdAction<Control> {

	private static final long serialVersionUID = 7032237140396163292L;
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private FieldService fieldService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ControlService controlService;

	private List<Field> listField;
	private List<Activity> listActivity;
	private List<Control> listControl;
	private List<View> listViews;
	private String appId;
	private String fieldControls;

	private View dataView;

	@Override
	protected void doList() throws Exception {
		logger.debug("<进入>:doList方法   获取字段列表");
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		String flowId = application.getFlowId();
		String flowKey = application.getFlowKey();
		getFields(application);
		//根据fromId获取活动集合
		listActivity = activityService.getActivityByFlow(flowId,flowKey);
		Object[] objs = new Object[]{appId,flowId,formId};
		listControl = controlService.findControlByObjects(objs);
		listViews = new ArrayList<View>();
		if (listControl != null) {
			for (int i = 0; i < listControl.size(); i++) {
				View view = new View();
				view.setName(listControl.get(i).getActivityName());
				if (StringUtils.isNotBlank(listControl.get(i).getFieldControl())) {
					view.setCheckStr(listControl.get(i).getFieldControl());
				} else {
					String fieldControl = "";
					for (int j = 0; j < listField.size(); j++) {
						if (i == 0) {
							fieldControl += "W";
						} else {
							fieldControl += "R";
						}
					}
					view.setCheckStr(fieldControl);
				}
				listViews.add(view);
			}
		} else {
			for (int i = 0; i < listActivity.size(); i++) {
				View view = new View();
				view.setName(listActivity.get(i).getActivityName());
				String fieldControl = "";
				for (int j = 0; j < listField.size(); j++) {
					if (i == 0) {
						fieldControl += "W";
					} else {
						fieldControl += "R";
					}
				}
				view.setCheckStr(fieldControl);
				listViews.add(view);
			}
		}
	}
	/**
	 *
	* @author _zili
	* @Description:获取字段列表，修改原因为有外置表单、外置公文、外置表单和意见、外置公文和意见类型
	* @date 2015年4月16日 上午10:53:30
	 */
    @SuppressWarnings("rawtypes")
	public void getFields(Application app){
    	logger.debug("<进入>:getFields方法   获取字段列表");

    	AppHandle handle = app.getHandle();

		String javaClass = handle.getHandleJava();

		Object obj = ObjectUtils.getInstance(javaClass);
		FormHandle formHandle = (FormHandle) obj;
		listField =formHandle.getFields(app);
    }

    /**
     *
    * @author _zili
    * @Description:保存字段读写性。所有关于control的数据，都是先保存字段读写性才生成。前端也作控制了。
    * @date 2015年4月20日 下午3:34:31
     */
	public String saveActivity(){
		logger.debug("<进入>:saveActivity方法   保存字段读写性");
		try {
			Application application = applicationService.get(appId);
			String formId = application.getForm().getFormId();
			String flowId = application.getFlowId();
			String comId = AppContext.getCurrentComId();

			String[] controlNames = dataView.getName().split(",");
			String activityName = "";
			for(int i = 0; i<controlNames.length; i++){
			    activityName = controlNames[i].trim();

			    entity = new Control();
				entity.setCompanyId(comId);
				entity.setAppId(appId);
				entity.setFormId(formId);
				entity.setFlowId(flowId);
				entity.setActivityName(activityName);
				String sj = dataView.getCheck().get(i).replace(", ", "");
				Object[] objs = new Object[]{appId,flowId,activityName,formId};
				Control control = controlService.getControlByObjects(objs);
				if(control!=null){
					control.setFieldControl(sj);
					control.setControlId(control.getControlId());
					controlService.save(control);
				}else{
  				    entity.setFieldControl(sj);
					controlService.save(entity);
				}
			}
			setResult(ActionResult.SUCCESS, "保存成功!");
			LogUtil.log(ModuleConstant.FIELD_READ_WRITE, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "保存字段读写性");
		} catch (Exception e) {
			setResult(ActionResult.FAIL, "保存失败！");
			logger.error("<错误>:保存字段读写性失败",e);
		}
		return JSON;
	}

	public List<Field> getListField() {
		return listField;
	}

	public void setListField(List<Field> listField) {
		this.listField = listField;
	}

	public List<Activity> getListActivity() {
		return listActivity;
	}

	public void setListActivity(List<Activity> listActivity) {
		this.listActivity = listActivity;
	}

	public List<Control> getListControl() {
		return listControl;
	}

	public void setListControl(List<Control> listControl) {
		this.listControl = listControl;
	}

	public List<View> getListViews() {
		return listViews;
	}

	public void setListViews(List<View> listViews) {
		this.listViews = listViews;
	}

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public String getFieldControls() {
		return fieldControls;
	}

	public void setFieldControls(String fieldControls) {
		this.fieldControls = fieldControls;
	}
  public View getDataView() {
    return dataView;
  }
  public void setDataView(View dataView) {
    this.dataView = dataView;
  }

}
